﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WFNetLib;
using System.IO.Ports;
using System.Threading;
using System.Diagnostics;
using System.Windows.Forms;
using WFNetLib.GSMModem;
using WFNetLib.Forms;
using WFNetLib.Net;
using System.IO;
using System.IO.Compression;
using System.Net;

namespace QueryBookTicket
{
    public class QueryBookTicketThread
    {
        public SerialPort Com;
        public Thread ReaderThreadIns=null;
        public static event strEventHandler AddLogEvent;//事件声明
        public static event intstrEventHandler FinishEvent;//事件声明
#if DEBUG
        CommunicationDebugForm CommunicationDebugForm;
#endif


        GsmModem gsmModem;
        public string PortName;
        public int ComIndex;
        void OnAddLog(string strLog)
        {
            if (AddLogEvent != null)
            {  
                AddLogEvent(this,new strEventArgs(strLog));
            }
        }
        void OnFinishEvent(int n)
        {
            if (FinishEvent != null)
            {
                FinishEvent(this, new intstrEventArgs(n));
            }
        }
        void OnFinishEvent(int n,string str)
        {
            if (FinishEvent != null)
            {
                FinishEvent(this, new intstrEventArgs(n,str));
            }
        }
        public QueryBookTicketThread(SerialPort _Com,int index)
        {
            Com = _Com;
            
#if DEBUG
            CommunicationDebugForm = new CommunicationDebugForm();
            //CommunicationDebugForm.IsClose = true;
            CommunicationDebugForm.Show();
            CommunicationDebugForm.Text = Com.PortName + "数据检测";
            gsmModem = new GsmModem(Com,CommunicationDebugForm);
#else
            gsmModem = new GsmModem(Com);
#endif

            ComIndex = index;
            gsmModem.dIP[0] = 10;
            gsmModem.dIP[1] = 0;
            gsmModem.dIP[2] = 0;
            gsmModem.dIP[3] = 172;
            gsmModem.dPort = 80;       
            gsmModem.AddLog += new strEventHandler(gsmModem_AddLog);
            
        }

        void gsmModem_AddLog(object sender, strEventArgs e)
        {
            OnAddLog(e.strArg);
        }
        public void ReaderThreadStart()
        {
            ReaderThreadIns = new Thread(new ThreadStart(ReaderProc));
            ReaderThreadIns.Name = "查询" + Com.PortName;
            PortName = Com.PortName;
            ReaderThreadIns.Start();
            OnAddLog("查询开始");
        }
        private void ReaderProc()
        {
            //try
            {
                while (true)
                {
                    try
                    {
                        Com.Open();
                        //Com.RtsEnable = true;
                    }
                    catch
                    {
                        OnAddLog("串口无法打开,请终止软件");
                        OnFinishEvent((int)FinishType.Unkown);
                        break;
                    }
                    if (!gsmModem.InitGSMModem())
                    {
                        break;
                    }
                    OnAddLog("初始化成功");
                    if (!gsmModem.InitPPPConnect())
                    {
                        break;
                    }
                    OnAddLog("拨号成功");
                    string uri = "http://wap.cmread.com/sns/wap/p/myspace/myspace.jsp?layout=2";
                    WebHeaderCollection httpHeader = new WebHeaderCollection();
                    httpHeader[HttpRequestHeader.UserAgent] = "NokiaN82/1.0 (20.1.062) SymbianOS/9.2 Series60/3.1 Profile/MIDP-2.0 Configuration/CLDC-1.1";
                    //httpHeader[HttpRequestHeader.Accept] = "gzip";
                    httpHeader[HttpRequestHeader.AcceptEncoding] = "gzip";
                    httpHeader[HttpRequestHeader.AcceptLanguage] = "zh-CN, en-US";
                    CookieCollection cookies = new CookieCollection();
                    string tx = HttpStatic.HttpHeaderToStr(uri, httpHeader, cookies);
                    object o;
                    OnAddLog("查询中-----");
//                     if (gsmModem.strATI == "HUAWEIGTM900")
//                     {
//                         o = gsmModem.GTM900_TCPIPRead(tx);
//                     }
//                     else
//                     {
                        if (!gsmModem.TCPRead(new List<byte>(Encoding.ASCII.GetBytes(tx))))
                        {
                            OnAddLog("获得tcp数据失败!");
                            OnFinishEvent((int)FinishType.Unkown);
                            break;
                        }

                        o = gsmModem.TCPData.oTCPDatas;
                    //}
                    if (o == null)
                        break;
                    Http http = (Http)o;
                    string str = "";
                    if (http.ContentDatas.Count == 0)
                        break;
                    str = HttpStatic.ContentToStr(http);
                    int x = str.IndexOf("onevent type=\"onenterforward\"");
                    if (x != -1)
                    {
                        x = str.IndexOf("go href=\"", x);
                        if (x != -1)
                        {
                            x += 9;
                            OnAddLog("获得跳转页");
                            httpHeader[HttpRequestHeader.Referer] = uri;
                            uri = WFNetLib.Strings.StringsFunction.strDecode(str.Substring(x, str.IndexOf('\"', x) - x));
                            if (http.Cookies.Count != 0)
                            {
                                foreach (Cookie c in http.Cookies)
                                {
                                    if (cookies[c.Name] != null)
                                        cookies[c.Name].Value = c.Value;
                                    else
                                        cookies.Add(c);
                                }
                            }
                            tx = HttpStatic.HttpHeaderToStr(uri, httpHeader, cookies);
                            if (!gsmModem.TCPRead(new List<byte>(Encoding.ASCII.GetBytes(tx))))
                            {
                                OnAddLog("获得tcp数据失败!");
                                OnFinishEvent((int)FinishType.Unkown);
                                break;
                            }

                            o = gsmModem.TCPData.oTCPDatas;
                        }
                    }
                    if (o == null)
                        break;
                    http = (Http)o;
                    OnAddLog("获得结果页");
                    str = HttpStatic.ContentToStr(http);
                    OnAddLog("断开连接");
                    if (!gsmModem.pppClose())
                    {
                        OnAddLog("ppp关闭失败");
                    }
                    else
                    {
                        OnAddLog("ppp关闭成功");
                    }
                    string PhoneNum="";
                    string Ticket="";
                    x = str.IndexOf("手机号码：");
                    if (x != -1)
                    {
                        x += "手机号码：".Length;
                        PhoneNum = str.Substring(x, 11);
                    }
                    else
                        PhoneNum = "未知手机号码";
                    OnAddLog("手机号码:" + PhoneNum);
                    x = str.IndexOf("书券余额:");
                    if (x != -1)
                    {
                        x += "书券余额:".Length;
                        Ticket = str.Substring(x, str.IndexOf("元", x) - x);
                        OnFinishEvent((int)FinishType.Finish, PhoneNum + ";" + Ticket);
                        OnAddLog("书券余额:" + Ticket);
                    }
                    else
                    {
                        OnFinishEvent((int)FinishType.UnkownTicket);
                        OnAddLog("未知书券余额:");
                    }
                    Com.Close();
                    return;
                }
                OnAddLog("<未知退出>");
                OnFinishEvent((int)FinishType.Unkown);
                Com.Close();
             }
//              catch (System.Exception ex)
//              {
//                  if (!gsmModem.pppClose())
//                  {
//                      OnAddLog("ppp关闭失败");
//                  }
//                  else
//                  {
//                      OnAddLog("ppp关闭成功");
//                  }
//                  OnAddLog("<未知退出>"+ex.Message);
//                  OnFinishEvent((int)FinishType.Unkown);
//                  Com.Close();
//              }
            
        }        
    }
}
